package com.zretc.support.service.serviceimpl;

import com.zretc.support.dao.TopicmultDao;
import com.zretc.support.entity.Topicmult;
import com.zretc.support.service.TopicmultService;
import com.zretc.support.tool.RandomTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TopicmultServiceImpl implements TopicmultService {

    @Autowired
    TopicmultDao topicmultDao;

    Logger logger = LoggerFactory.getLogger(TopicmultServiceImpl.class);

    @Override
    public List<Topicmult> getAllTopic() {
        return topicmultDao.findAll();
    }

    @Override
    public Topicmult addTopicmult(Topicmult topicmult) {
        RandomTopic randomTopic = new RandomTopic();
        String topicIdB = "B"+randomTopic.getRandom();
        Topicmult Test = null;
        try{
            Test = topicmultDao.findByChooseId(topicIdB);
        }catch (NullPointerException e){

        }
        if(Test == null){
            topicmult.setChooseId(topicIdB);
            topicmult = topicmultDao.save(topicmult);
        }else{
            addTopicmult(topicmult);
        }
        return topicmult;
    }

    @Override
    public int delTopicmult(String topicmultId) {
        try{
            topicmultDao.deleteById(topicmultId);
            return 1;
        }catch(Exception e){
            return 0;
        }
    }

    @Override
    public int updTopicmult(Topicmult topicmult) {
        topicmultDao.save(topicmult);
        return 0;
    }

    @Override
    public Page<Topicmult> getTopicmultByPage(String keyword,String level,String type, int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size);
        return topicmultDao.getTopicmultByPage(keyword,level,type,pageable);
    }

    @Override
    public Page<Topicmult> getTopicmultByCourseIdWithPage(List<Long> courseId, String level, String type, int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size);
        return topicmultDao.getTopicmultByCourseIdWithPage(courseId,level,type,pageable);
    }

    @Override
    public Page<Topicmult> getTopicmultByRand(int course, int num, int type) {
        Pageable pageable = PageRequest.of(0,num);
        Page<Topicmult> page = null;
        if(type == 1){
            page = topicmultDao.getRandomChooseSingle(course,pageable);
        }else if(type == 2){
            page = topicmultDao.getRandomChooseMult(course,pageable);
        }
        return page;
    }

    @Override
    public Topicmult getTopicmultById(String topicId) {

        return topicmultDao.findByChooseId(topicId);
    }
}
